<template>
  <div class="row">
    <q-list style="width: 300px">
      <q-item>
        <q-select
          class="full-width"
          :dark="ui.isDark"
          filled
          v-model="group"
          :options="groupOptions"
          :display-value="` ${
            group
              ? $t('routeManage.当前分组') + group
              : $t('routeManage.请选择分组')
          }`"
        >
          <template v-if="group" v-slot:append>
            <q-icon
              name="cancel"
              @click.stop.prevent="group = ''"
              class="cursor-pointer"
            />
          </template>
          <template v-slot:no-option>
            <q-item>
              <q-item-section class="text-grey">
                <!--                No options slot-->
                {{ $t("routeManage.暂无分组") }}
              </q-item-section>
            </q-item>
          </template>
        </q-select>
      </q-item>
      <q-item>
        <q-btn
          class="full-width"
          :class="ui.btnClass"
          icon="add"
          @click="dialogAdd.show()"
        />
      </q-item>
      <q-scroll-area style="width: 100%; height: calc(100vh - 180px)">
        <template v-for="item in postureList" :key="item.id">
          <q-item v-show="!group || item.group === group">
            <q-btn
              no-caps
              class="full-width q-pa-none"
              :class="
                activePosture.id === item.id ? ui.activeClass : ui.itemClass
              "
              @click="choosePosture(item)"
            >
              <div class="fit row justify-between">
                <div class="col-2"></div>
                <span class="q-ma-none col-7" style="line-height: 36px">{{
                  item.name
                }}</span>
                <q-icon
                  name="edit"
                  color="white"
                  class="col-2"
                  size="1.5rem"
                  @click.stop="dialogAdd.show(item)"
                ></q-icon>
              </div>
            </q-btn>
          </q-item>
        </template>
      </q-scroll-area>
    </q-list>
    <div
      ref="postureDiv"
      style="width: calc(100vw - 300px); overflow: hidden"
    ></div>
    <posture-point ref="dialogAdd" @refresh="updateList" />
    <list-show-small
      v-if="
        activePosture &&
        activePosture.onCanvas &&
        pixiTool.savedList.filter(
          (item) => item.onCanvas && item.id !== activePosture.id
        ).length
      "
      @update="updateLine"
      @switchChange="(val) => (switchStatus = val)"
      ref="lineListDialog"
      :position="'top:125px'"
      :needReset="false"
      :needSwitch="true"
      :switchStatus="switchStatus"
      :title="activePosture.name || ''"
      :optionsList="pixiTool.savedList.filter((item) => item.onCanvas)"
      :selectedList="activePosture.connected || []"
    />
    <div class="absolute-center row" style="top: 75px">
      <q-btn
        no-caps
        :label="$t('routeManage.重载')"
        :class="ui.btnClass"
        @click="loadPosture"
      />
      <q-btn
        no-caps
        :label="$t('routeManage.保存')"
        :class="ui.btnClass"
        @click="saveList"
        class="q-ml-sm"
      />
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref } from "vue";
import { api } from "boot/axios";
import { useQuasar } from "quasar";
import { useUiStore } from "stores/ui";
import { useAPIStore } from "stores/api";
import { useFunctionsStore } from "stores/functions";
import { storeToRefs } from "pinia";
import PixiTool from "src/utils/PixiTool";
import PosturePoint from "components/posture/PosturePoint.vue";
import ListShowSmall from "components/map/ListShowSmall.vue";
import { useI18n } from "vue-i18n";

const t = useI18n().t;
const $q = useQuasar();
const ui = useUiStore();
const { scene } = storeToRefs(useFunctionsStore()); //  当前场景
const pixiTool = PixiTool();
const postureDiv = ref();
const lineListDialog = ref();
const activePosture = ref({});
const group = ref("");
const groupOptions = ref([]);
const postureList = ref([]);
const dialogAdd = ref(); // 添加弹框
const switchStatus = ref(false); //  查看连线的弹窗是否默认开启

onMounted(() => {
  getGroupList();
  initPixi();
});

// 获取分组列表
function getGroupList() {
  const params = {
    scenario: scene.value.id,
    type: "normal",
  };
  api
    .get(useAPIStore().postureUrl + "new/posture/groups", { params })
    .then((rs) => {
      if (rs.data.code !== 200)
        return $q.notify({
          message: t("routeManage.分组列表获取失败"),
          type: "negative",
        });
      groupOptions.value = rs.data.data;
    })
    .catch(() => {
      $q.notify({
        message: t("routeManage.分组列表获取异常"),
        type: "negative",
      });
    });
}

// 创建画布
function initPixi() {
  pixiTool.div = postureDiv.value;
  pixiTool.stage = pixiTool.createStage(postureDiv.value);
  // 覆写点位点击事件
  pixiTool.clickPoint = choosePosture;
  // 覆写点位移入移出事件
  pixiTool.isOnCanvas = changeCanvas;
  loadBg();
}

// 加载背景
function loadBg() {
  const bgImage = new Image();
  bgImage.src = "posture/bg.png";
  bgImage.onload = () => {
    pixiTool.bg = pixiTool.createBg({
      img: bgImage,
    });
    pixiTool.createArea();
    loadPosture();
    pixiTool.updateStage();
  };
}

// 加载连线
function loadPosture() {
  if (!scene.value) return;
  const params = {
    scenario: scene.value.id,
    group: null,
    type: "normal",
  };
  api
    .get(useAPIStore().postureUrl + "new/posture", { params })
    .then((rs) => {
      if (rs.data.code !== 200)
        return $q.notify({
          message: t("routeManage.姿态列表获取失败"),
          type: "negative",
        });
      postureList.value = rs.data.data.filter(
        (item) => !!item.storage === false
      );
      // 加载姿态
      pixiTool.drawRail(postureList.value);
      $q.notify({ message: t("routeManage.加载姿态成功"), type: "positive" });
    })
    .catch(() => {
      $q.notify({
        message: t("routeManage.姿态列表获取异常"),
        type: "negative",
      });
    });
}

// 选中点位
function choosePosture(posture) {
  pixiTool.highlight(posture);
  activePosture.value = pixiTool.highlightPoint;
  // 是否需要连线弹窗
  if (switchStatus.value) {
    // 连线弹窗是否符合条件
    if (lineListDialog.value) lineListDialog.value.show();
  }
}

// 点位进入或移除画布
function changeCanvas(bool) {
  activePosture.value.onCanvas = !bool;
  activePosture.value.onCanvas = bool;
  // 如果点位移除，清除连线
  if (!bool) updateLine([]);
}

// 更新列表
function updateList(type, p) {
  switch (type) {
    case "create":
      postureList.value.unshift(p);
      break;
    case "modify": {
      const n = postureList.value.findIndex((item) => item.id === p.id);
      if (n >= 0) {
        postureList.value[n] = p;
      }
      break;
    }
    case "delete": {
      // 清除连线
      updateLine([]);
      // 清除当前点数据
      const n = postureList.value.findIndex((item) => item.id === p.id);
      if (n >= 0) {
        postureList.value.splice(n, 1);
      }
      break;
    }
  }
  getGroupList();
  pixiTool.drawRail(pixiTool.savedList);
}

// 保存点位
function saveList() {
  api
    .put(useAPIStore().postureUrl + "new/posture/batch", pixiTool.savedList)
    .then((rs) => {
      rs.data.code === 200
        ? $q.notify({ message: t("routeManage.保存成功"), type: "positive" })
        : $q.notify({
            message: t("routeManage.保存失败"),
            type: "negative",
          });
    });
}

// 更新连线
function updateLine(connected) {
  // 将选中点的新连线进行赋值
  activePosture.value.connected = connected;
  pixiTool.savedList.forEach((item) => {
    const index = item.connected.indexOf(activePosture.value.id);
    // 如果其他点对选中点有连接，进行断开，（先统一与选中点进行断开）
    if (index >= 0) item.connected.splice(index, 1);
    // 新连线的点对选中点进行连线
    if (connected.indexOf(item.id) >= 0)
      item.connected.push(activePosture.value.id);
  });
  pixiTool.drawRail();
}
</script>
